<template>
  <el-dialog
    class="public-dialog"
    title="面单管理"
    width="936"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
  >
    <div class="" v-loading="loading">
      <VForm
        class="shadow-[0_1px_0_0_#eff3fe] mt-[15px]"
        ref="form"
        :model="model"
        :fieldList="fieldList"
        :options="formOption"
        :originOption="optionsData"
        @submit="handleSearch"
        @reset="handleSearch"
      >
      </VForm>
      <div class="my-[8px]">
        <VActionBar :actions="actions" />
      </div>
      <div class="flex flex-wrap h-[460px] overflow-auto" v-loading="loading">
        <div
          v-for="item in list"
          :key="item.id"
          class="w-[208px] border-[1px] border-[#e6e7e9] px-[8px] py-[8px] rounded-[8px] mr-[12px] mb-[16px] h-[344px]"
        >
          <div
            class="relative w-[192px] h-[192px] rounded-[8px] bg-[#f7f7f7] overflow-hidden"
          >
            <el-image
              class="w-[100%] h-[100%]"
              :src="
                item?.bill_img ||
                'https://react.dev/images/home/videos/documentary.webp'
              "
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="[
                item?.bill_img ||
                  'https://react.dev/images/home/videos/documentary.webp',
              ]"
              :initial-index="4"
              fit="cover"
            />
            <el-checkbox
              class="absolute top-[0] right-[8px]"
              :model-value="selected.includes(item.id)"
              @change="handleChangeSelect(item.id, $event)"
            >
            </el-checkbox>
          </div>
          <div
            class="text-[16px] text-[#333] leading-[22px] mt-[8px] text-ellipsis"
          >
            <p class="truncate">{{ item.bill_name }}</p>
            <p class="text-[14px]">{{ item.bill_lang || "-" }}</p>
            <p class="text-[14px]">
              {{ item.bill_size_l }}*{{ item.bill_size_w }}cm
            </p>
          </div>
          <div class="text-[12px] leading-[17px] mt-[4px]">
            <p class="text-[#666]">创建人：{{ item.create_user }}</p>
            <p class="text-[#999]">{{ item.create_time }}</p>
          </div>
          <div class="flex items-center justify-between">
            <el-switch
              :modelValue="item.status"
              :beforeChange="handleChangeStatus(item.id, item.status)"
              inline-prompt
              active-text="启用"
              inactive-text="禁用"
              :active-value="1"
              :inactive-value="0"
            ></el-switch>
            <div
              class="flex items-center text-[14px] leading-[20px] text-[#3487ff] cursor-pointer"
            >
              <span @click="handleEdit(item.id)">编辑</span>
              <el-divider direction="vertical"></el-divider>
              <span @click="handleSetBill(item)">面单</span>
              <!-- <el-divider direction="vertical"></el-divider> -->
              <!-- <span>复制</span> -->
              <el-divider direction="vertical"></el-divider>
              <span class="text-[#e50113]" @click="handleDelete(item.id)">
                删除
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <add
      v-model="addVisible"
      :type="type"
      @close="idRef = ''"
      :id="idRef"
      @refresh="handleRefresh"
    />
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? "关闭" : "取消" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from "element-plus";
import VForm from "@/components/Form/index.vue";
import ActionBar from "@/components/ActionBar/index.vue";
import add from "./add/index.vue";

import { billList, billStatus, billDelete } from "./api";
const router = useRouter();
const props = defineProps({
  modelValue: { type: Boolean, default: false },
  type: { type: String, default: "logistics-type" },
  disabled: { type: Boolean, default: false },
});

const { proxy } = getCurrentInstance();

const list = ref([]);
const selected = ref([]);
const emit = defineEmits(["update:modelValue", "refresh", "close"]);
const search = ref({});
const loading = ref(false);
const addVisible = ref(false);
const idRef = ref("");

const form = ref();
const model = ref({});
const optionsData = ref({});

onMounted(() => {
  getList();
});

const getList = async () => {
  try {
    loading.value = true;
    const { type } = props;
    const { data } = await billList(type, search.value);
    list.value = data;
  } catch (e) {
    console.error(e);
  } finally {
    loading.value = false;
  }
};

const formOption = {
  inline: true,
  labelPosition: "top",
  option: true,
  showResetButton: true,
};

const handleChangeStatus = (id, status) => async () => {
  const { type } = props;
  await billStatus(type, { id, status: status ? 0 : 1 });
  await getList();
};

const handleChangeSelect = (id, e) => {
  const _select = selected.value;
  const _index = _select.indexOf(id);
  if (_index > -1) {
    selected.value.splice(_index, 1);
  } else {
    selected.value.push(id);
  }
};

const getSelect = () => {
  const _select = selected.value;
  if (!_select.length) {
    ElMessage.warning("请至少选择一条数据");
    return [];
  }
  return _select;
};

const handleEdit = (id) => {
  idRef.value = id;
  addVisible.value = true;
};
const handleSetBill = (item) => {
  console.log(item);
  router.push({
    path: `/logistics-settings/bill-logistics/design`,
    query: {
      id: item.id,
      type: props.type,
      bill_size_l: item.bill_size_l,
      bill_size_w: item.bill_size_w,
    },
  });
};
const handleStatus = async (flag) => {
  const _id = getSelect();
  if (!_id.length) return;
  await handleChangeStatus(_id, !flag)();
  selected.value = [];
};

const publicStyle = { style: { width: "262px" } };
const fieldList = [
  {
    field: "bill_name",
    ...publicStyle,
    placeholder: "面单名称",
  },
  {
    field: "status",
    type: "select",
    options: {
      placeholder: "状态",
      data: [
        { label: "全部", value: "" },
        { label: "启用", value: 1 },
        { label: "禁用", value: 0 },
      ],
    },
    ...publicStyle,
  },
];

const handleBatchDelete = async () => {
  const _id = getSelect();
  if (!_id.length) return;
  await handleDelete(_id);
  selected.value = [];
};

const handleDelete = (id) => {
  const { type } = props;
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认删除选中的
        <span class="text-[#3366F1] px-[4px]">{id.length || 1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          await billDelete(type, { id });
          ElMessage.success("操作成功");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          getList();
        }
      } else {
        done();
      }
    },
  });
};

const handleSearch = (e) => {
  search.value = e;
  nextTick(() => {
    getList();
  });
};

const handleRefresh = async () => {
  await getList();
  emit("refresh");
};

const handleClose = async (refresh) => {
  model.value = {};
  await nextTick();
  form.value.resetForm();
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};

const actions = [
  {
    label: "新增",
    icon: "add2",
    type: "primary",
    fn: () => (addVisible.value = true),
  },
  { label: "删除", icon: "del", fn: handleBatchDelete },
  {
    label: "启用",
    icon: "state_finish_line",
    fn: () => handleStatus(true),
  },
  {
    label: "禁用",
    icon: "state_disabled",
    fn: () => handleStatus(false),
  },
];
</script>
